<template>
  <div class="fr content">
    <div class="container">
      <div class="content-box">
        <p>
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>最新文章</el-breadcrumb-item>
            <el-breadcrumb-item class="nav-title text-ellipsis">
              <el-tooltip effect="dark" :content="data.title" placement="top">
                <div>
                  {{ data.title }}
                </div>
              </el-tooltip>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </p>
        <hr />
        <div style="min-height: 500px">
          <p class="title">
            <strong>
              {{ data.title }}
            </strong>
          </p>
          <p class="publish_time" align="left">
            发布时间: {{ data.publishDate }}
            <span style="margin-left: 12px">By <a href="#">{{ checkUser.nickname }}</a></span>
            <span style="margin-left: 12px" v-if="user && user.id && data.userId && user.id === data.userId"><a @click="goEdit">&nbsp;编辑</a></span>
          </p>
          <p class="markdown-body" v-html="data.content" v-highlight></p>
        </div>
      </div>
      <div class="author-box">
        <div>
          <span
            ><b>本文作者：</b><a href="#">{{ checkUser.nickname }}</a></span
          ><br />
          <span><b>本文链接：</b>www.xxx.xxx</span><br />
          <span
            ><b>关于博主: </b>评论和私信会在第一时间回复。或者<a href="#"
              >直接私信</a
            >我</span
          ><br />
          <span
            ><b>版权声明：</b>本博客所有文章除特别声明外，均采用
            <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/">
              BY-NC-SA </a
            >许可协议。转载请注明出处！</span
          ><br />
          <span
            ><b>声援博主：</b>如果您觉得文章对您有帮助，可以点击后面<span
              style="color: red"
              >【</span
            ><a href="#">打赏</a
            ><span style="color: red">】</span
            >。您的鼓励是博主的最大动力！</span
          ><br />
        </div>
      </div>
      <div class="comment-box">
        <div class="comment-title">
          评论区 (共{{ commentList.length }}条评论)
        </div>

        <!-- 评论区 -->
        <div v-if="commentList.length != 0">
          <div
            class="commnets-box"
            v-for="(item, index) in commentList"
            :key="index"
          >
            <div class="comments-user-header">
              <el-avatar
                icon="el-icon-user-solid"
                :size="48"
                shape="circle"
                :src="`${serveIp}${item.user.avatar||''}`"
                fit="fill"
              ></el-avatar>
              <span class="name">
                {{ item.user.nickname||'' }}
                <br />
                <span class="time"
                  >{{ datetime(item.commentTime)||'' }}</span
                >
              </span>
            </div>
            <div class="comments-content">
              <p class="post-content" v-highlight v-html="item.content||''"></p>
            </div>
          </div>
        </div>
        <el-empty
          :image-size="100"
          :description="'暂无评论，赶快来抢首发吧！'"
          v-else
        ></el-empty>

        <div class="comment-submit-box">
          <textarea
            placeholder="参与评论，与博主互动，无限制发言哦！"
            v-model="commentContent"
            class="comment-content-box"
          ></textarea>
          <b-button
            style="min-width: 80px"
            variant="outline-success"
            class="my-2 my-sm-0 submit-comment-button"
            type="submit"
            @click="commentClick"
            >发表</b-button
          >
        </div>
      </div>
    </div>

    <div class="right-container d-none d-xl-block">
      <user-box></user-box>
      <!-- <hot-box></hot-box>
      <recommend-box></recommend-box> -->
    </div>
  </div>
</template>

<script>
import UserBox from "../userBox.vue";
import HotBox from "../hotBox.vue";
import RecommendBox from "../recommendBox.vue";

import PressApi from "../../api/press";
import CommonApi from "../../api/common";


import DateFormat, { mask } from "dateformat";
export default {
  data() {
    return {
      user: {
        id: undefined,
        nickname: '',
        avatar: ''
      },
      serveIp: "",
      data: {
        title: "",
        content: ``,
        sourceContent:``,
        publishDate: "",
        username: "",
        userId: undefined
      },
      commentContent: "",
      commentList: [],
    };
  },
  components: {
    UserBox,
    HotBox,
    RecommendBox,
  },
  methods: {
    replaceImageUrl(content) {
      if (!content || !this.serveIp) return content;
      return content.replace(/<img[^>]+src="([^">]+)"/g, (match, src) => {
        // 提取路径中的 /upload/images/... 部分
        const pathMatch = src.match(/\/upload\/images\/.*$/);
        if (pathMatch) {
          return `<img src="${this.serveIp}${pathMatch[0]}"`;
        }
        return match;
      });
    },
    goEdit(){
      console.log(this.data.user.id == this.data.userId)
      this.$router.push({ path: `/publishPress?id=${this.data.id}` })
    },
    editClick() {
      if (this.checkUser.id === this.data.userId) {
        this.goEdit()
      } else {
        this.$message.warning("你没有权限进行编辑！");
      }
      return false;
    },
    commentClick() {
      if (this.commentContent.trim() != "") {
        let submitData = {
          content: this.commentContent,
          pressId: this.data.id,
        };
        PressApi.addComment(submitData).then((r) => {
          if (r.code === 200) {
            this.$message.success("评论成功!");

            let user = JSON.parse(window.localStorage.getItem("userInfo"));

            
            const nowDate = new Date();
            this.commentList.push({
              content: this.commentContent,
              user: {
                nickname: user.nickname,
                avatar: user.avatar,
              },
              commentTime: nowDate,
            });
            this.commentContent = "";
          }
        });
      }
    },
    getData(val = this.$route.params.id) {
      PressApi.getPress(val).then((r) => {
        if (r.code === 200) {
          this.data = r.data;
          this.data.content = this.replaceImageUrl(this.data.content);
          document.title = this.data.title;
          PressApi.getComment(this.data.id).then((commentsResult) => {
            if (commentsResult.code === 200) {
              this.commentList = commentsResult.data;
            }
          });
        }
      });
    },
    datetime(val) {
      return DateFormat(val, "yyyy年 mm月 dd日 HH:MM:ss") ;
      // return val;
    },
  },
  async created() {
    let tempUser = window.localStorage.getItem("userInfo");
    console.log(tempUser);
    
    if (tempUser) {
      this.user = JSON.parse(tempUser);
    }
    try {
      const response = await CommonApi.getIp();
      this.serveIp = `${response.data}`;
      console.log(this.serveIp);
      
    } catch (error) {
      console.error('获取IP失败:', error);
      this.serveIp = ''; // 设置默认值
    }
    this.getData();
  },
  computed: {
    checkUser() {
      return this.data.user
        ? this.data.user
        : {
            id: "",
            username: "",
            nickname: "",
            password: "",
            birthday: "",
            age: "",
            avatar: "",
            description: "",
            email: "",
            phone: "",
            state: "",
            createTime: "",
          };
    },
  },
};
</script>

<style lang="scss" scoped>

@import "/public/mavon-editor/markdown/github-markdown.min.css";
.content {
  justify-content: center;
  margin: 0 auto;
  position: relative;
  left: 0;
  transition: all 1s;
}
::v-deep ol,
::v-deep ul,
::v-deep dl {
  margin-left: 24px !important;
}
.container {
  // min-width: 50%;
  min-height: 980px;
  max-width: 1100px;
  margin: 24px 0px 24px 0px;
  transition: all 0.3s;
  .content-box,
  .author-box,
  .comment-box {
    padding: 24px;
    border-radius: var(--box-radius);
    background-color: var(--bg-color);
    backdrop-filter: var(--bg-filter-blur);
    box-shadow: var(--box-shadow);
  }
  .nav-title {
    max-width: 240px;
  }
  .el-breadcrumb__item {
    margin-top: 12px;
  }
  .title {
    font-size: 28px;
    font-weight: lighter;
  }
  .publish_time {
    color: #4e4e4e;
    font-size: 12px;
    a {
      color: var(--font-color-hover);
      transition: 0.4s;
    }
    a:hover {
      color: var(--font-color-active);
      text-decoration: none;
    }
  }
  .author-box {
    min-height: 200px;
    padding: 24px;
    margin-top: 24px;
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-items: end;
  }
  .comment-box {
    min-height: 300px;
    padding: 24px;
    margin-top: 24px;
    display: flex;
    flex: 1;
    flex-direction: column;
    justify-items: end;
    .commnets-box {
      margin-bottom: 24px;
      border-bottom: 1px solid #c2c2c2;
      .comments-user-header {
        display: flex;
        flex-direction: row;
        flex: 1;
        align-items: center;
        .name {
          margin-left: 12px;
        }
        .time {
          font-size: 12px;
        }
      }
      .comments-content {
        padding: 24px 0 0px 0;
      }
    }
    .comment-title {
      font-size: 14px;
      border-bottom: 1px solid #999999;
      padding: 0 0 12px 0;
      margin-bottom: 24px;
    }
    ::v-deep .ck,
    .ck-toolbar {
      background: #ffffff1e !important;
    }
    ::v-deep .ck-content {
      min-height: 120px !important;
    }
    .comment-submit-box {
      margin-top: 48px;
      text-align: right;
      .submit-comment-button {
        width: 100px;
        margin-top: 18px !important;
      }
      .comment-content-box {
        padding:8px;
        width: 100%;
        min-height: 100px;
      }
    }
  }
}
.right-container {
  min-width: 400px;
  padding: 24px 24px 24px 24px;
  transition: 0.3s;
  > div {
    padding: 24px;
    width: 100%;
    background-color: var(--bg-color);
    backdrop-filter: var(--bg-filter-blur);
    box-shadow: var(--box-shadow);
    border-radius: var(--box-radius);
  }
  > div:nth-of-type(n + 2) {
    margin-top: 24px;
  }
}

@media (min-width: 1600px) {
  .content{
    left: 7%;
  }
}
@media (max-width: 528px) {
  .container {
    padding: 0 !important;
    margin: 12px 0;
  }
}

</style>